package cn.iocoder.yudao.module.dify.config;

import lombok.extern.slf4j.Slf4j;
import net.sourceforge.tess4j.ITesseract;
import net.sourceforge.tess4j.Tesseract;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.net.URL;
import java.nio.file.Paths;

@Slf4j
@Configuration
public class TesseractOCRConfig {

    @Bean
    public ITesseract tesseract() {
        ITesseract tesseract = new Tesseract();
        try {
        // 安全地获取tessdata路径
        URL tessDataURL = getClass().getClassLoader().getResource("tessdata");
        if (tessDataURL == null) {
            throw new RuntimeException("Cannot find tessdata directory in resources");
        }
        String tessDataPath = Paths.get(tessDataURL.toURI()).toString();
        tesseract.setDatapath(tessDataPath);
        // 设置默认语言
        tesseract.setLanguage("chi_sim+eng");

        // 设置OCR引擎模式
        tesseract.setOcrEngineMode(1); // 使用LSTM OCR引擎

        // 设置页面分割模式
        tesseract.setPageSegMode(6); // 假设一个统一的文本块
        } catch (Exception e) {
            log.error("Failed to initialize Tesseract OCR, falling back to English only", e);
        }
        return tesseract;
    }
}
